package com.netease.financial.base.splash;

import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.netease.financial.BuildConfig;
import com.netease.financial.R;
import com.netease.financial.common.constant.Constants;
import com.netease.financial.common.util.ImageUtil;
import com.netease.financial.common.util.preferences.AppUpdatePreferencesHelper;
import com.netease.financial.internal.di.components.DaggerSplashComponent;
import com.netease.financial.internal.di.components.SplashComponent;
import com.netease.financial.internal.di.modules.SplashModule;
import com.netease.financial.ui.activity.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class SplashActivity extends BaseActivity implements SplashView, View.OnClickListener {

    private static final int SPLASH_START_VIEW_HIDE_DELAY_MILLIS = 2000;

    private static final int REQUEST_CODE_PREVIEW_PDF = 1;

    private TypedArray mSplashImageIds;
    private String[] mSplashTitles;
    private String[] mSplashSkips;
    private String[] mSplashSummaries;
    private String[] mSplashComments;
    private String[] mSplashGoToMains;

    private SplashViewModel splashViewModel;

    @Bind(R.id.splash_start)
    ImageView splash_start;

    @Bind(R.id.banner_splash_pager)
    BGABanner banner;

    @Bind(R.id.bnt_view_agreement)
    Button btnViewAgreement;

    SplashComponent splashComponent;

    @Inject
    SplashPresenter splashPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        initializeInjector();
        initialize();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        mHideHandler.removeCallbacks(mHideRunnable);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PREVIEW_PDF) {
            goToMain();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initialize() {
        Resources res = getResources();
        mSplashImageIds = res.obtainTypedArray(R.array.share_item_icons);
        mSplashTitles = res.getStringArray(R.array.splash_guide_titles);
        mSplashSkips = res.getStringArray(R.array.splash_guide_skips);
        mSplashSummaries = res.getStringArray(R.array.splash_guide_summaries);
        mSplashComments = res.getStringArray(R.array.splash_guide_comments);
        mSplashGoToMains = res.getStringArray(R.array.splash_guide_go_to_mains);
    }

    private void initializeInjector() {
        this.splashComponent = DaggerSplashComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(getActivityModule())
                .splashModule(new SplashModule(
                        getResources().getDisplayMetrics().widthPixels,
                        getResources().getDisplayMetrics().heightPixels,
                        Constants.PLATFORM
                ))
                .build();
        this.splashComponent.inject(this);
    }

    private void initBanner() {
        // 用Java代码方式设置切换动画
//        banner.setTransitionEffect(BGABanner.TransitionEffect.Rotate);
//        banner.setPageTransformer(new RotatePageTransformer());
        banner.setPageChangeDuration(1000);
        banner.setViews(getPageViews());
        banner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                // 如果是最后一页,则禁止向前滑动,并且隐藏indicator
                if (position == mSplashTitles.length - 1) {
                    banner.setViewPagerScrollEnabled(false);
                    banner.showPoints(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private View getPageContainer() {
        return getLayoutInflater().inflate(R.layout.layout_splash_page, null);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        this.splashPresenter.setView(this);
        this.splashPresenter.initialize();
        this.splashPresenter.refreshLaunchPage();

        delayedHide(SPLASH_START_VIEW_HIDE_DELAY_MILLIS);
    }

    private void hide() {
        boolean needGuide = AppUpdatePreferencesHelper.isSplashGuideNeedShow();
        if (needGuide) {
            this.splash_start.setVisibility(View.GONE);
            banner.setVisibility(View.VISIBLE);
            initBanner();
        } else {
            goToMain();
        }

    }

    private final Handler mHideHandler = new Handler();
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    private void delayedHide(int delayMillis) {
        if (BuildConfig.DEBUG) {
            finish();
            goToMain();
            return;
        }
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }

    private void setBtnViewAgreementState() {
        if (splashViewModel != null && splashViewModel.isViewAgreementEnabled()) {
            btnViewAgreement.setVisibility(View.VISIBLE);
            btnViewAgreement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mHideHandler.removeCallbacks(mHideRunnable);
                    getNavigator().navigateToPreviewOnlinePdf(SplashActivity.this, splashViewModel.getAgreementUrl(), REQUEST_CODE_PREVIEW_PDF);
                }
            });
        } else {
            btnViewAgreement.setVisibility(View.GONE);
        }
    }

    private List<View> getPageViews() {
        int pageCount = mSplashTitles.length;
        List<View> views = new ArrayList<>();
        for (int i = 0; i < pageCount; i++) {
            View splashPage = getPageContainer();
            ImageView splashImage = ButterKnife.findById(splashPage, R.id.splash_image);
            splashImage.setImageResource(getPageImageResource(i));

            initTextView(splashPage, R.id.skip, mSplashSkips[i], true);
            initTextView(splashPage, R.id.splash_title, mSplashTitles[i], false);
            initTextView(splashPage, R.id.splash_summary, mSplashSummaries[i], false);
            initTextView(splashPage, R.id.splash_comment, mSplashComments[i], false);
            initTextView(splashPage, R.id.btn_go_to_main, mSplashGoToMains[i], true);

            views.add(splashPage);
        }
        return views;
    }

    private void initTextView(View parentView, int viewId, String text, boolean clickable) {
        TextView textView = ButterKnife.findById(parentView, viewId);
        textView.setText(text);
        if (!TextUtils.isEmpty(text)) {
            textView.setVisibility(View.VISIBLE);
        }
        if (clickable) {
            textView.setOnClickListener(this);
        }
    }

    private int getPageImageResource(int index) {
        return mSplashImageIds.getResourceId(index, R.drawable.guide_page_0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.skip:
            case R.id.btn_go_to_main:
                goToMain();
                AppUpdatePreferencesHelper.setLastVersionCodeForShowSplash();
                break;
            default:
                break;
        }
    }

    @Override
    protected boolean shouldShowChatBall() {
        return false;
    }

    @Override
    protected boolean shouldProtectedByLockPattern() {
        return false;
    }

    private void goToMain() {
        getNavigator().navigateToMainScreen(this);
        finish();
    }

    @Override
    public void showLaunchPage(SplashViewModel viewModel) {
        this.splashViewModel = viewModel;
        setBtnViewAgreementState();
        delayedHide(viewModel.getDuration());
        ImageUtil.displayImage(splash_start, viewModel.getLaunchPageImageUrl(), R.drawable.splash_start);
    }

}
